/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package epaper;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Puneet
 */
public class Mint extends CommonClient implements Callable {

    private final String username = "epaperDownloader%40live.com";
    private final String password = "download";


    public Mint(String fileName, Date date) {
        super(null, -1, fileName, date);
    }


    public void buildURL(String lang, Date date) {

       
        Format format = new SimpleDateFormat("dd_MM_yyyy");
        String dateStr = format.format(date);
        urlStr = new StringBuilder("http://epaper.livemint.com/PDFHandler.ashx?p1=Web&p2=");
        //20_04_2011_001.pdf");
        urlStr.append(dateStr.toString()).append("_");
        mergePaper = new StringBuilder(basefile + "MINT");
        mergePaper.append("_").append(dateStr.toString()).append(".pdf");

        System.out.println("urlStr : " + urlStr);
    }

    /**
     * @param args the command line arguments
     */
    @Override
    public String call() {
        try {
            System.out.println("********************************************************");
            System.out.println("***********    CREATED BY -- Punit Agrawal   ***********");
            System.out.println("*******    Contact me @ punit.agrawal@wsu.edu  *********");
            System.out.println("********************************************************");
            System.out.println("");
            //String[] arg = {"MAIN","ENG","MUM"};
            basefile = fileName;
            if (!fileName.endsWith("\\") && !fileName.endsWith("/")) {
                basefile += "/";
            }
            buildURL(lang, date);
            System.out.println("GETTING PDFs !!!! ");
            String data = "__EVENTTARGET=submit&__EVENTARGUMENT=&txtUserID=" + username + "&txtPassword=" + password;
            URL url = new URL("http://epaper.livemint.com/login.aspx");
            //HttpURLConnection uc = (HttpURLConnection)url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)));
            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            uc.setRequestProperty("Referer", "http://epaper.livemint.com/login.aspx");
            uc.setRequestMethod("POST");
            uc.setDoInput(true);
            uc.setDoOutput(true);
            uc.setInstanceFollowRedirects(false);
            uc.connect();
            OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
            wr.write(data);
            wr.flush();
            /*BufferedReader rd = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
            // Process line...
            System.out.println(line);
            }
             * */
            wr.close();
            //rd.close();
            Map<String, List<String>> headers = uc.getHeaderFields();
            List<String> values = headers.get("Set-Cookie");
            Map<String, String> cookies = new HashMap<String, String>();
            //String cookieValue = null;
            for (Iterator iter = values.iterator(); iter.hasNext();) {
                String cookieValue = (String) iter.next();
                cookies.put(cookieValue.substring(0, cookieValue.indexOf("=")), cookieValue.substring(cookieValue.indexOf("=") + 1, cookieValue.indexOf(";")));
            }
            /*for(String s:cookies.keySet()) {
            System.out.println("Key : "+s+ " Value : "+cookies.get(s));
            }*/
            /*for(String s:cookies.keySet()) {
            System.out.println("Key : "+s+ " Value : "+cookies.get(s));
            }*/
            ExecutorService es = Executors.newFixedThreadPool(pagecount);
            for (int i = 0; i < pagecount; i++) {
                int j = i + 1;
                final String localStr = urlStr.toString() + getThreeDigitString(j) + ".pdf";
                System.out.println("localStr : " + localStr);
                Callable<ByteArrayInputStream> c = new Worker(localStr, i, "MINT", cookies);
                futures.add(es.submit(c));
            }
            for (Future<ByteArrayInputStream> f : futures) {
                try {
                    InputStream i = f.get();
                    if (i != null) {
                        pdfs.add(i);
                    }
                } catch (InterruptedException ex) {
                    //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ExecutionException ex) {
                    //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                    if (!(ex.getCause() instanceof NullPointerException)) {
                        try {
                            throw ex;
                        } catch (ExecutionException ex1) {
                            Logger.getLogger(Mint.class.getName()).log(Level.SEVERE, null, ex1);
                        }
                    }
                }
            }
            es.shutdown();
            url = new URL("http://epaper.livemint.com/logout.aspx");
            //HttpURLConnection uc = (HttpURLConnection)url.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("localhost", 8080)));
            uc = (HttpURLConnection) url.openConnection();
            uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            uc.setRequestProperty("Referer", "http://epaper.livemint.com/Default.aspx?BMode=100");
            String myCookie = "ASP.NET_SessionId=" + cookies.get("ASP.NET_SessionId") + "; IsUserReg=True";
            uc.setRequestProperty("Cookie", myCookie);
            uc.setRequestMethod("GET");
            uc.setInstanceFollowRedirects(false);
            uc.connect();
            //Combine the pdfs
            UI.getInstance().setTaskInProgress("Merging PDFs");
            System.out.println("MERGING PDFs");
            MyPDFUtility.mergeStreams(pdfs, mergePaper.toString());
            System.out.println("PDFs MERGED");
            WorkProgress.getInstance().increment(100);
            return mergePaper.toString().replace('\\', File.separatorChar).replace('/', File.separatorChar);
        } catch (IOException ex) {
            Logger.getLogger(Mint.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }


     public  String buildPageUrl(int pagenumber){
         return null;
     }

    @Override
    public void buildURL(String lang, int city, Date date) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
